<script setup>
import { ref, onMounted } from "vue";
// 导入依赖
import FileSaver from 'file-saver';
import XLSX from 'xlsx';

let action = ref(0);
let logs = ref([]);
let index = 0;
let ISDataList = [];
let boxs = [];
let tableData = ref([]);

onMounted(async () => {
  const page = localStorage.getItem("page");
  if (location.href?.includes("item.ht")) {
    subTask();
  } else if (page) {
    setTimeout(() => {
      startCrawl();
    }, 6000);
  }
});

// 开始抓取
const startCrawl = async () => {
  console.log("开始抓取");
  logs.value.push({
    type: "info",
    content: `开始抓取`,
  });
  action.value = 1;
  localStorage.setItem("status", "1");
  // 开始抓取
  const boxList = document.querySelectorAll(".skin-box-bd .item");
  const dataList = [];
  const itemList = [];
  // 更新数据
  boxList.forEach((box) => {
    // 获取data-id
    const dataId = box.getAttribute("data-id");
    if (dataId) {
      let TextData = box.querySelector("dd.detail")?.innerText;
      TextData = TextData?.split("\n");
      itemList.push(box.childNodes[box.childNodes.length - 2]?.children[0]);
      const dataObj = {
        id: dataId,
        dataTitle: TextData[0],
        price: null,
      };
      let match = TextData[TextData.length - 1].match(/\d+/);
      if (match) {
        // 销售量
        dataObj.dataSales = match[0];
      }
      dataList.push(dataObj);
    }
  });

  // 更新数据
  ISDataList = dataList;
  boxs = itemList;
  console.log("抓取到", boxs);
  logs.value.push({
    type: "success",
    content: `抓取到${dataList.length}个商品`,
  });

  const page = localStorage.getItem("page");
  if (page) {
    requestData(
      "https://api.hhxcaz.top/taobao/push",
      {
        data: dataList,
        logs: logs.value,
        status: localStorage.getItem("status") ? 1 : 0,
      },
      "POST"
    ).then((res) => {
      console.log("更新数据完成(追加数据)");
      if (res.data) {
        clickProduct();
      }
    });
  } else {
    requestData(
      "https://api.hhxcaz.top/taobao/",
      {
        data: dataList,
        logs: logs.value,
        status: localStorage.getItem("status") ? 1 : 0,
      },
      "POST"
    ).then((res) => {
      console.log("更新数据完成");
      if (res.data) {
        clickProduct();
      }
    });
  }
};

// 点击商品
const clickProduct = async () => {
  console.log("开始点击商品");
  const status = localStorage.getItem("status");
  if (status !== "1") {
    return;
  }
  logs.value.push({
    type: "info",
    content: `开始点击第${index + 1}商品`,
  });
  console.log("商品", boxs[index]);
  boxs[index].click();
  index++;
  if (index < ISDataList.length) {
    setTimeout(() => {
      clickProduct();
    }, 7000);
  } else {
    // 更新数据
    logs.value.push({
      type: "success",
      content: `当页数据抓取完成`,
    });
    // action.value = 0;
    const page = localStorage.getItem("page");
    if (page) {
      localStorage.setItem("page", Number(page) + 1);
    } else {
      localStorage.setItem("page", 1);
    }
    // 页面滑倒最底下
    window.scrollTo(0, document.body.scrollHeight);
    setTimeout(() => {
      document.querySelector("a.next").click();
    });
  }
};

// 子任务
const subTask = async () => {
  console.log("子任务");
  const status = await requestData("https://api.hhxcaz.top/taobao/");
  if (!(status.code == 200 && status.status)) {
    return;
  }

  // 使用正则表达式匹配id的值
  let idMatch = location.href.match(/\bid=([^&]+)/);
  // 如果找到了匹配项，则idMatch[1]将包含id的值
  let id = idMatch ? idMatch[1] : null;

  // 更新数据
  const price = document.querySelector(
    "span.Price--priceText--2nLbVda"
  )?.innerText;
  if (!price) {
    logs.value.push({
      type: "error",
      content: `请完成验证!`,
    });
    setTimeout(() => {
      subTask();
    }, 5000);
    return;
  }

  requestData(
    "https://api.hhxcaz.top/taobao/p",
    { id: id, price: price },
    "POST"
  ).then((res) => {
    if (res.code == 200) {
      setTimeout(() => {
        window.close();
      }, 1000);
    }
  });
};

// 请求数据
const requestData = (url, data = {}, method = "GET") => {
  return new Promise((resolve, reject) => {
    window
      .fetch(url, {
        method: method,
        headers: {
          "Content-Type": "application/json",
        },
        body: method == "GET" ? null : JSON.stringify(data),
      })
      .then((res) => resolve(res.json()))
      .catch((err) => reject(err));
  });
};

// 结束抓取
const stopCrawl = () => {
  localStorage.removeItem("status");
  action.value = 0;
  requestData("https://api.hhxcaz.top/taobao/", {
    logs: logs.value,
    status: action.value,
  });
};

// 清除数据
const clearData = () => {
  localStorage.removeItem("status");
  logs.value = [];
  ISDataList = [];
  index = 0;
  action.value = 0;
  requestData("https://api.hhxcaz.top/taobao/clear");
};

// 导出数据
const exportData = async () => {
  const res = await requestData("https://api.hhxcaz.top/taobao/");
  console.log('导出数据');
  if (res.code == 200) {
    tableData.value = res.data;
    // 导出数据
    const data = XLSX.utils.json_to_sheet(tableData.value); //此处tableData.value为表格的数据
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, data, "test-data"); //test-data为自定义的sheet表名
    XLSX.writeFile(wb, "test.xlsx"); //test.xlsx为自定义的文件名
  } else {
    console.log("导出数据失败");
  }
};
</script>

<template>
  <div class="home">
    <div class="btnBox">
      <el-button type="primary" :disabled="action !== 0" @click="startCrawl"
        >开始抓取</el-button
      >
      <el-button type="warning" :disabled="action !== 1" @click="stopCrawl"
        >结束抓取</el-button
      >
      <el-button type="success" @click="exportData">导出数据</el-button>
      <el-button type="danger" @click="clearData">清除数据</el-button>
    </div>
    <div class="logview">
      <div v-for="(item, index) in logs" :key="index">
        .....
        <el-text :type="item.type">{{ item.content }}</el-text>
      </div>
    </div>
  </div>
</template>
<style scoped>
.home {
  padding: 10px 20px;
}
.logview {
  padding: 10px;
  height: 160px;
  margin-top: 10px;
  background-color: black;
  color: #fff;
  border-radius: 5px;
  line-height: 1.3;
  overflow: auto;
}
</style>
